package com.fanchuan.uzx.rest;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.fanchuan.uzx.beans.LectureData;
import com.fanchuan.uzx.beans.LecturePrefs_;
import com.fanchuan.uzx.beans.OfferData;
import com.fanchuan.uzx.beans.OfferEntity;
import com.fanchuan.uzx.beans.LectureData.LectureEntity;
import com.fanchuan.uzx.db.LectureDB;
import com.fanchuan.uzx.db.LectureDBDao;
import com.fanchuan.uzx.db.OfferDB;
import com.fanchuan.uzx.db.OfferDBDao;
import com.fanchuan.uzx.rest.UZXRest.LockObject;
import com.fanchuan.uzx.ui.utils.DialogUtils;

public class LectureRest {

	private static String LECTURE_URL = UZXRest.BASE_URL + "page=%d&type=3&total=%d";
	private LecturePrefs_ mPrefs;
	private LectureDBDao mLectureDBDao;
	private AQuery query;
	private Context context;
	public LectureRest(Context mContext, LecturePrefs_ prefs, LectureDBDao dao){
		context = mContext;
		setOfferPrefs(prefs);
		this.mLectureDBDao = dao;
		query = new AQuery(mContext);
	}
	
	public void setOfferPrefs(LecturePrefs_ mPrefs){
		this.mPrefs = mPrefs;
	}
	
	void setPrefHasNextPage(boolean hasNextPage) {
		mPrefs.edit().hasNextPage().put(hasNextPage).apply();
	}

	void setPrefNextPage(int next_page) {
		mPrefs.edit().nextPage().put(next_page).apply();
	}
	
	void setHasMoredata(boolean hasData){
		mPrefs.edit().hasMoreData().put(hasData).apply();
	}
	
	public boolean refresh(){
		final int page = 1;
		setHasMoredata(true);
		mPrefs.edit().total().put(0).apply();
//		final LockObject lock = new LockObject();
//		AjaxCallback<String> callback = new AjaxCallback<String>(){
//			@Override
//			public void callback( String url, String object, AjaxStatus status) {
//				onResult(lock, object, page, true);
//			}
//		};
//		query.ajax(String.format(LECTURE_URL, page, mPrefs.total().get()), String.class, 7*24*60*60*1000, callback);
//		lock.waitForResult(30 * 1000);
//		return lock.getResult();
		
		AjaxCallback<String> callback = new AjaxCallback<String>();
		callback.url(String.format(LECTURE_URL, page, mPrefs.total().get())).type(String.class);
		query.sync(callback);
		return onResult(callback.getResult(), page, true);
	}
	
	public boolean onResult(String result , int page, boolean clear_before_insert){
		if(TextUtils.isEmpty(result)){
			//maybe network error
			
			return false;
		}
		Log.d("result", "result:"+result);
		try {
			JSONObject object = new JSONObject(result);
			String objStr = object.getString("list");
			if(objStr != null && objStr.equals("[0]")){
				setPrefHasNextPage(false);
				setHasMoredata(false);
				return false;
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		LectureData data = Jsoner.getInstance().fromJson(result, LectureData.class);
		LectureEntity[] lectures = data.list;
		if(lectures == null || lectures.length == 0){
			setPrefHasNextPage(false);
			return false;
		}
		if(clear_before_insert){
			mLectureDBDao.deleteAll();
		}
		
		for(LectureEntity f : lectures){
			long count = mLectureDBDao.queryBuilder().where(LectureDBDao.Properties.Id.eq(f.id)).count();
			if(count >0){
				continue;
			}
			
			LectureDB lectureDB = new LectureDB(f.id, f.id, f.title, f.time, f.content, page);
			mLectureDBDao.insert(lectureDB);
		}
		
		setPrefHasNextPage(true);
		setPrefNextPage(page+1);
		return true;
	}
	
//	public void onResult(LockObject lock,String result, int page, boolean clear_before_insert){
//		if(TextUtils.isEmpty(result)){
//			//maybe network error
//			lock.setResult(false);
//			lock.notifyResult();
//			return;
//		}
//		Log.d("result", "result:"+result);
//		try {
//			JSONObject object = new JSONObject(result);
//			String objStr = object.getString("list");
//			if(objStr != null && objStr.equals("[0]")){
//				setPrefHasNextPage(false);
//				setHasMoredata(false);
//				lock.setResult(false);
//				lock.notifyResult();
//				return ;
//			}
//			
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		LectureData data = Jsoner.getInstance().fromJson(result, LectureData.class);
//		LectureEntity[] lectures = data.list;
//		if(lectures == null || lectures.length == 0){
//			setPrefHasNextPage(false);
//			lock.setResult(false);
//			lock.notifyResult();
//			return ;
//		}
//		if(clear_before_insert){
//			mLectureDBDao.deleteAll();
//		}
//		
//		for(LectureEntity f : lectures){
//			long count = mLectureDBDao.queryBuilder().where(LectureDBDao.Properties.Id.eq(f.id)).count();
//			if(count >0){
//				continue;
//			}
//			
//			LectureDB lectureDB = new LectureDB(f.id, f.id, f.title, f.time, f.content, page);
//			mLectureDBDao.insert(lectureDB);
//		}
//		
//		setPrefHasNextPage(true);
//		setPrefNextPage(page+1);
//		lock.setResult(true);
//		lock.notifyResult();
//	}
	
	public boolean getNextPage(){
		if(!DialogUtils.checkNetWork(context)){
			return false;
		}
//		final LockObject lock = new LockObject();
//		final int page = mPrefs.nextPage().get();
//		AjaxCallback<String> callback = new AjaxCallback<String>(){
//			@Override
//			public void callback(String url, String object, AjaxStatus status) {
//				onResult(lock,object, page, false);
//			}
//		};
//		query.ajax(String.format(LECTURE_URL, page, mPrefs.total().get()), String.class, 7*24*40*60*1000, callback);
//		
//		lock.waitForResult(30 * 1000);
//		return lock.getResult();
		final int page = mPrefs.nextPage().get();
		AjaxCallback<String> callback = new AjaxCallback<String>();
		callback.url(String.format(LECTURE_URL, page, mPrefs.total().get())).type(String.class);
		query.sync(callback);
		return onResult(callback.getResult(), page, false);
	}
}
